package com.lz.library.base

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.lz.library.dialog.ProgressDialog
import com.lz.library.extension.findGenericClass

/**
 *  author: you : 2020/04/20
 */
abstract class BaseActivity<VM : BaseViewModel<*>, B : ViewDataBinding> : AppCompatActivity(), IView {

    //ViewDataBinding
    private var _binding: B? = null
    protected val binding: B get() = _binding!!

    //ViewModel
    protected lateinit var viewModel: VM
        private set

    //进度弹窗
    private val progressDialog: ProgressDialog by lazy { ProgressDialog(this) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        init()

        viewModel = initViewModel()
        lifecycle.addObserver(viewModel)
        viewModel.dialogEvent.observe(this) { if (it) showLoading() else hideLoading()  }
        viewModel.finishEvent.observe(this) { if (it) finish() }
        initObserve()

        _binding = DataBindingUtil.setContentView(this, getLayoutRes())
        binding.lifecycleOwner = this
        getVMVariableId()?.also { binding.setVariable(it, viewModel) }
        initData(savedInstanceState)
    }

    override fun onDestroy() {
        super.onDestroy()
        lifecycle.removeObserver(viewModel)
        binding.unbind()
        _binding = null
    }

    protected open fun init() = Unit

    protected open fun initObserve() = Unit

    protected open fun initData(savedState: Bundle?) = Unit

    //Binding ViewModel
    protected open fun getVMVariableId(): Int? = null

    /**
     * 默认使用activity中的ViewModelStoreOwner, override
     * @return
     */
    protected open fun initViewModel(): VM =
        ViewModelProvider(this)[javaClass.findGenericClass(BaseViewModel::class.java)!!]

    override fun showLoading() {
        if (!progressDialog.isShowing) progressDialog.show()
    }

    override fun hideLoading() {
        if (progressDialog.isShowing) progressDialog.dismiss()
    }
}